import axios, { AxiosError, AxiosRequestHeaders, AxiosResponse } from "axios";

export const CODE_MESSAGE: Record<number, string> = {
  400: "Bad Request",
  401: "Unauthorized",
  403: "Forbidden",
  404: "Not Found",
  502: " Bad Gateway",
  503: "Service Unavailable",
  504: "Gateway Timeout"
};

export const useHost = (baseUrl: string) => {
  axios.defaults.baseURL = baseUrl;
};

export const useToken = (token: string, key = "Token") => {
  axios.defaults.headers.common[key] = token;
};

export const get = <T = any>(url: string, query: Record<string, string | number> = {}, headers?: AxiosRequestHeaders): Promise<T> => {
  return axios.get<T>(url, { params: query, headers }) as unknown as Promise<T>;
};
export const post = <T = any>(url: string, body: Object = {}, headers?: AxiosRequestHeaders): Promise<T> => {
  return axios.post<T>(url, body, { headers }) as unknown as Promise<T>;
};
export const put = <T = any>(url: string, body: Object = {}, headers?: AxiosRequestHeaders): Promise<T> => {
  return axios.put<T>(url, body, { headers }) as unknown as Promise<T>;
};
export const del = (url: string, query: Record<string, string | number> = {}, headers?: AxiosRequestHeaders): Promise<void> => {
  return axios.delete(url, { params: query, headers });
};

axios.defaults.withCredentials = true;

axios.interceptors.response.use(
  (res: AxiosResponse<{ body: any; code: number }>) => {
    if (res.data.code && res.data.code !== 200) {
      throw res.data;
    }
    return res.data.body || res.data;
  },
  (err: AxiosError<{ code: number; message: string }>) => {
    return Promise.reject(err.response?.data);
  }
);

export const onRequestErr = (func: (err: { code: number; message: string }) => void) => {
  axios.interceptors.response.use(undefined, func);
};
